<template>
    <div :class="['toolbar-wrapper', showSidebar ? 'toolbar-show' : 'toolbar-hide']">
        <span v-if="!showToolbar" class="toolbar-txt">工具栏</span>
        <div @click="handleShowToolbar">
            <img v-if="showToolbar" class="image" :src="getImageUrl('toolbar_up')">
            <img v-else class="image" :src="getImageUrl('toolbar_down')">
        </div>
        <div v-if="showToolbar" class="tools">
            <div class="tool-item" @click="hideSidebar">
                <img v-if="showSidebar" class="tool-icon" :src="getImageUrl('yincang')">
                <img v-else class="tool-icon" :src="getImageUrl('yincang1')">
                <span class="tool-txt">隐藏</span>
            </div>
            <div class="tool-item" @click="openMeasurePanel">
                <img v-if="activeTool == 'measure'" class="tool-icon" :src="getImageUrl('measure_selected')">
                <img v-else class="tool-icon" :src="getImageUrl('measure_normal')">
                <span class="tool-txt">测量</span>
                <div class="panel measure-panel" v-if="activeTool == 'measure'">
                    <div class="tool-item" @click="handleSection">
                        <img v-if="sectionStatus" class="tool-icon" :src="getImageUrl('pouqie1')">
                        <img v-else class="tool-icon" :src="getImageUrl('pouqie')">
                        <span class="tool-txt">剖切</span>
                    </div>
                    <div class="tool-item" @click="handleDistanceMeasure">
                        <img v-if="distanceMeasureStatus" class="tool-icon" :src="getImageUrl('ceju1')">
                        <img v-else class="tool-icon" :src="getImageUrl('ceju')">
                        <span class="tool-txt">测距</span>
                    </div>
                    <div class="tool-item" @click="handleAreaMeasure">
                        <img v-if="areaMeasureStatus" class="tool-icon" :src="getImageUrl('cemian1')">
                        <img v-else class="tool-icon" :src="getImageUrl('cemian')">
                        <span class="tool-txt">测面</span>
                    </div>
                </div>
            </div>

            <div class="tool-item" @click="handleScreenshot">
                <img v-if="activeTool == 'jiePing'" class="tool-icon" :src="getImageUrl('jieping1')">
                <img v-else class="tool-icon" :src="getImageUrl('jieping')">
                <span class="tool-txt">截屏</span>
            </div>
            <div class="tool-item" @click="handleRecord">
                <img v-if="activeTool == 'luPing'" class="tool-icon" :src="getImageUrl('luping1')">
                <img v-else class="tool-icon" :src="getImageUrl('luping')">
                <span class="tool-txt">录屏</span>
            </div>
            <div class="tool-item" @click="openBookmarkPanel">
                <img v-if="activeTool == 'bookmark'" class="tool-icon" :src="getImageUrl('shuqian1')">
                <img v-else class="tool-icon" :src="getImageUrl('shuqian')">
                <span class="tool-txt">书签</span>
                <div class="panel weather-panel" v-if="activeTool == 'bookmark'">
                    <div class="tool-item" style="position: relative;" v-for="(item, index) in bookmarkData"
                        :key="index" @click.stop="gotoBookmark(item)">
                        <img v-if="activeMark == item.Name" class="tool-icon" :src="getImageUrl('shuqianlist1')">
                        <img v-else class="tool-icon" :src="getImageUrl('shuqianlist')">
                        <span class="tool-txt">{{ item['Name'] }}</span>
                        <img class="del-icon" :src="getImageUrl('del')" @click.stop="deleteBookmark(item['ID'])">
                    </div>
                    <div class="tool-item" @click.stop="handleAddBookmark">
                        <img class="tool-icon" :src="getImageUrl('shuqian_add')">
                        <span class="tool-txt">添加</span>
                    </div>
                </div>
            </div>
            <div class="tool-item" style="position: relative" @click="openRoamPanel">
                <img v-if="activeTool == 'roam'" class="tool-icon" :src="getImageUrl('roam1')">
                <img v-else class="tool-icon" :src="getImageUrl('roam')">
                <span class="tool-txt">漫游</span>
                <div class="panel measure-panel" v-if="activeTool == 'roam'">
                    <div class="tool-item" v-for="roam in roamTypes" :key="roam.type"
                        @click.stop="setRoamScenario(roam.type)">
                        <img v-if="roamScenario == roam.type" class="tool-icon" :src="getImageUrl('route1')">
                        <img v-else class="tool-icon" :src="getImageUrl('route')">
                        <span class="tool-txt">{{ roam.label }}</span>
                        <span class="tool-txt">{{ roam.keymap }}</span>
                    </div>
                </div>
            </div>
            <div class="tool-item" style="position: relative" @click="openWeatherPanel">
                <img v-if="activeTool == 'tianQi'" class="tool-icon" :src="getImageUrl('tianqi1')">
                <img v-else class="tool-icon" :src="getImageUrl('tianqi')">
                <span class="tool-txt">天气</span>
                <div class="panel " v-if="activeTool == 'tianQi'">
                    <div class="sync-wrap">
                        <span class="time_label">天气与现实同步</span>
                        <div @click.stop="syncWeather">
                            <img v-if="syncWeatherStatus" class="sync_img"
                                src="../assets/images/time/ic_synchronous_selected.png">
                            <img v-else class="sync_img" src="../assets/images/time/ic_synchronous_normal.png">
                        </div>
                    </div>
                    <div class="weather-panel">
                        <div class="tool-item" v-for="(item, index) in weatherData" :key="index"
                            @click.stop="handleChangeWeather(item.value)">
                            <img v-if="activeWeather == item.value" class="tool-icon" :src="getImageUrl(item.icon1)">
                            <img v-else class="tool-icon" :src="getImageUrl(item.icon)">
                            <span class="tool-txt">{{ item['label'] }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div v-if="showDownload" class="tool-item" @click="downloadExcelData">
                <img v-if="activeTool == 'downData'" class="tool-icon" :src="getImageUrl('down1')">
                <img v-else class="tool-icon" :src="getImageUrl('down2')">
                <span class="tool-txt">下载</span>
                <span class="tool-txt">数据</span>
            </div>
            <div v-if="showDownload" class="tool-item" @click="loadReport">
                <img v-if="activeTool == 'downReport'" class="tool-icon" :src="getImageUrl('down1')">
                <img v-else class="tool-icon" :src="getImageUrl('down2')">
                <span class="tool-txt">下载</span>
                <span class="tool-txt">报告</span>
            </div>
        </div>
    </div>
    <div :class="['roam_panel', isPlaying ? 'playing_roam_panel' : 'normal_roam_panel']" v-if="activeTool == 'roam'">
        <div class="tool-item" @click="handleRoamPlay">
            <img v-if="roamPlay" class="tool-icon" :src="getImageUrl('startRoaming_selected', 'ic')">
            <img v-else class="tool-icon" :src="getImageUrl('startRoaming_normal', 'ic')">
            <span class="tool-txt">开始</span>
            <span class="tool-txt">T</span>
        </div>
        <div class="tool-item" @click="handleRoamPause">
            <img v-if="roamPause" class="tool-icon" :src="getImageUrl('pauseRoaming_selected', 'ic')">
            <img v-else class="tool-icon" :src="getImageUrl('pauseRoaming_normal', 'ic')">
            <span class="tool-txt">暂停</span>
            <span class="tool-txt">T</span>
        </div>
        <div class="tool-item" @click="handleRoamReset">
            <img v-if="roamReset" class="tool-icon" :src="getImageUrl('resetRoaming_selected', 'ic')">
            <img v-else class="tool-icon" :src="getImageUrl('resetRoaming_normal', 'ic')">
            <span class="tool-txt">重置</span>
            <span class="tool-txt">R</span>
        </div>
    </div>
</template>
<script setup>
import { ref, getCurrentInstance, nextTick, watch, onMounted, onUnmounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import html2canvas from 'html2canvas';
import { recordScreen, fileDownload, } from '@/utils';
import { getBookmarks, delBookmark, addBookmark, downloadReport, downloadExcel } from '@/api/base';
import { useStore } from '@/stores';
import { getWeatherByCityLoc } from '@/utils/weather';
const { proxy } = getCurrentInstance();
const route = useRoute();
const bus = proxy.$bus;
const dayjs = proxy.$dayjs;
const store = useStore();

const showToolbar = computed(() => store.showToolbar);
const showSidebar = computed(() => store.showSidebar);
const showDownload = ref(false);
const downloadTableName = ref('');
const activeTool = ref('');

const activeWeather = ref('');
const bookmarkData = ref([]);
const activeMark = ref('');
const isPlaying = ref(false);

const weatherData = ref([
    { label: '晴天', value: 'clearSkies', icon: 'qingtian', icon1: 'qingtian1', alias: ['晴', '热'] },
    { label: '多云', value: 'cloudy', icon: 'duoyun', icon1: 'duoyun1', alias: ['多云', '少云'] },
    { label: '小雨', value: 'lightRain', icon: 'xiaoyu', icon1: 'xiaoyu1', alias: ['阵雨', '小雨', '毛毛雨/细雨', '阵雨'] },
    { label: '中雨', value: 'rain', icon: 'zhongyu', icon1: 'zhongyu1', alias: ['中雨', '小到中雨', '中到大雨', '强阵雨', '雨'] },
    { label: '雾', value: 'foggy', icon: 'wu', icon1: 'wu1', alias: ['薄雾', '雾', '浓雾', '强浓雾', '大雾', '特强浓雾'] },
    { label: '阴天', value: 'overcast', icon: 'yin', icon1: 'yin1', alias: ['阴', '冷'] },
    { label: '局部多云', value: 'partlyCloudy', icon: 'jubuduoyun', icon1: 'jubuduoyun1', alias: ['晴间多云'] },
    { label: '暴雨', value: 'thunderstorm', icon: 'baoyu', icon1: 'baoyu1', alias: ['强阵雨', '雷阵雨', '强雷阵雨', '雷阵雨伴有冰雹', '大雨', '极端降雨', '暴雨', '大暴雨', '特大暴雨', '冻雨', '大到暴雨', '暴雨到大暴雨', '大暴雨到特大暴雨'] },
    { label: '浮尘', value: 'sandDustCalm', icon: 'fuchen', icon1: 'fuchen1', alias: ['霾', '扬沙', '浮尘', '中度霾', '重度霾', '严重霾'] },
    { label: '沙尘暴', value: 'sandDustStorm', icon: 'shachenbao', icon1: 'shachenbao1', alias: ['沙尘暴', '强沙尘暴'] },
    { label: '小雪', value: 'lightSnow', icon: 'xiaoxue', icon1: 'xiaoxue1', alias: ['小雪', '雨夹雪', '雨雪天气', '阵雨夹雪', '阵雪', '雪'] },
    { label: '中雪', value: 'snow', icon: 'zhongxue', icon1: 'zhongxue1', alias: ['中雪', '小到中雪'] },
    { label: '暴雪', value: 'blizzard', icon: 'baoxue', icon1: 'baoxue1', alias: ['大雪', '暴雪', '中到大雪', '大到暴雪'] },
]);
const syncWeatherStatus = ref(false);

const roamTypes = ref([
    { label: '小区道路', type: 'outdoor', keymap: 'Y' },
    { label: '居委会', type: 'indoor', keymap: 'Alt+Y' },
    { label: '地下停车场', type: 'parking', keymap: 'Ctrl+Y' }
]);
const roamPlay = ref(false);
const roamPause = ref(false);
const roamReset = ref(false);

onMounted(() => {
    bus.on("showDownload", (args) => {
        if (args) {
            showDownload.value = true;
            downloadTableName.value = args.id;
        } else {
            showDownload.value = false;
            downloadTableName.value = "";
        }
    })
    bus.on('setSimulationMode', (mode) => {
        showDownload.value = false;
        downloadTableName.value = "";
    });
    bus.on("playingStatus", args => {
        if (args.step == args.totalSteps) {
            isPlaying.value = false;
        } else {
            isPlaying.value = true;
        }
    });
    document.addEventListener('keydown', keyHandler);
});
onUnmounted(() => {
    document.removeEventListener('keydown', keyHandler);
})
const keyHandler = (e) => {
    if (e.key === 'Escape') {
        sectionEnable.value = true;
        areaMeasureEnable.value = true;
        distanceMeasureEnable.value = true;
        distanceMeasureStatus.value = false;
        areaMeasureStatus.value = false;
    }
};
watch(() => store.cameraInfo, (newVal) => {
    bus.emit("keyboardInput", false);
    ElMessageBox.prompt('请输入书签名称', '添加书签', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.+$/,
        inputErrorMessage: '请输入书签名称'
    }).then(({ value }) => {
        const uid = route.query.uid;
        if (uid) {
            addBookmark(store.village, uid, value, newVal).then(res => {
                getBookmarkData();
            });
        } else {
            proxy.$toast("没有获取到uid");
        }
        bus.emit("keyboardInput", true);
    }).catch(() => {
        console.log("calcel input");
        bus.emit("keyboardInput", true);
    })
});

//剖切按钮是否可用
const sectionEnable = ref(true);
const sectionStatus = ref(false);
//测量距离按钮是否可用
const distanceMeasureEnable = ref(true);
const distanceMeasureStatus = ref(false);
//测量面积按钮是否可用
const areaMeasureEnable = ref(true);
const areaMeasureStatus = ref(false);
//漫游场景
const roamScenario = ref('');
//展开或收起工具栏
function handleShowToolbar() {
    store.setShowToolbar(!showToolbar.value);
}
//显示或隐藏侧边栏
function hideSidebar() {
    store.setShowSidebar(!showSidebar.value);
}
/**
 * 根据文件名获取文件链接
 * @param name 
 */
function getImageUrl(name, prefix = 'icon') {
    return new URL(`../assets/images/toolbar/${prefix}_${name}.png`, import.meta.url).href;
}
/**
 * 打开测量面板
 */
function openMeasurePanel() {
    activeTool.value = 'measure';
}
/**
 * 剖切
 * 剖切状态时,点击后终止剖切; 非剖切状态时,点击后开始剖切
 * 开启剖切状态后,测量距离和测量面积按钮需要禁用
 */
function handleSection() {
    activeTool.value = '';
    if (sectionEnable.value) {
        if (sectionStatus.value) {
            bus.emit("disableSection");
            sectionStatus.value = false;
            distanceMeasureEnable.value = true;
            areaMeasureEnable.value = true;
        } else {
            bus.emit("enableSection");
            sectionStatus.value = true;
            distanceMeasureEnable.value = false;
            areaMeasureEnable.value = false;
        }
    }
}
/**
 * 测量距离
 */
function handleDistanceMeasure() {
    activeTool.value = '';
    if (distanceMeasureEnable.value) {
        if (distanceMeasureStatus.value) {
            bus.emit("doDistanceMeasure", false);
            distanceMeasureStatus.value = false;
            sectionEnable.value = true;
            areaMeasureEnable.value = true;
        } else {
            bus.emit("doDistanceMeasure", true);
            distanceMeasureStatus.value = true;
            sectionEnable.value = false;
            areaMeasureEnable.value = false;
        }
    }
}
/**
 * 测量面积
 */
function handleAreaMeasure() {
    activeTool.value = '';
    if (areaMeasureEnable.value) {
        if (areaMeasureStatus.value) {
            bus.emit("doAreaMeasure", false);
            areaMeasureStatus.value = false;
            sectionEnable.value = true;
            distanceMeasureEnable.value = true;
        } else {
            bus.emit("doAreaMeasure", true);
            areaMeasureStatus.value = true;
            sectionEnable.value = false;
            distanceMeasureEnable.value = false;
        }
    }
}
/**
 * 截屏
 */
function handleScreenshot() {
    activeTool.value = 'jiePing';
    nextTick(() => {
        let el = document.getElementById("app");
        let opts = {
            // width: '100',
            // height: '100',
        }
        let fileName = dayjs().format('YYYYMMDDHHmmss') + '.jpg';
        html2canvas(el, opts).then((canvas) => {
            let imgData = canvas.toDataURL("image/jpeg"); // 转base64
            fileDownload(imgData, fileName);
        });
    });
}
/**
 * 录屏
 */
function handleRecord() {
    activeTool.value = 'luPing';
    let dateStr = dayjs().format('YYYYMMDDHHmmss');
    recordScreen(dateStr + ".webm");
}
/**
 * 打开书签面板
 */
function openBookmarkPanel() {
    activeTool.value = activeTool.value == 'bookmark' ? '' : 'bookmark';
    getBookmarkData();
}
/**
 * 打开漫游面板
 */
function openRoamPanel() {
    // activeTool.value = 'roam';
    console.log(1111);
    activeTool.value = activeTool.value == 'roam' ? '' : 'roam';
}
/**
 * 设置漫游场景
 * @param scenario 
 */
function setRoamScenario(scenario) {
    roamScenario.value = scenario;
    roamPlay.value = false;
    roamPause.value = false;
    roamReset.value = false;
    bus.emit("setRoamScenario", scenario);
}
/**
 * 开始漫游
 */
function handleRoamPlay() {
    console.log("开始漫游");
    if (!roamPlay.value) {
        roamPlay.value = true;
        roamPause.value = false;
        roamReset.value = false;
        bus.emit("roamPlay");
    }
}
/**
 * 暂停漫游
 */
function handleRoamPause() {
    console.log("暂停漫游");
    if (!roamPause.value) {
        roamPlay.value = false;
        roamPause.value = true;
        roamReset.value = false;
        bus.emit("roamPause");
    }

}
/**
 * 重置漫游
 */
function handleRoamReset() {
    console.log("重置漫游");
    if (!roamReset.value) {
        roamPlay.value = false;
        roamPause.value = false;
        roamReset.value = true;
        bus.emit("roamReset");
    }

}
/**
 * 打开天气设置面板
 */
function openWeatherPanel() {
    activeTool.value = activeTool.value == 'tianQi' ? '' : 'tianQi';
}
/**
 * 切换天气
 * @param weather 
 */
function handleChangeWeather(weather) {
    activeWeather.value = weather;
    syncWeatherStatus.value = false;
    bus.emit("changeWeather", weather);
}
/**
 * 同步天气
 */
function syncWeather() {
    syncWeatherStatus.value = !syncWeatherStatus.value;
    if (syncWeatherStatus.value) {
        const whLoc = import.meta.env.VITE_WEATHER_LOC;
        getWeatherByCityLoc(whLoc).then(res => {
            if (res && res['weather']) {
                let daily = res['weather']['daily'];
                const today = dayjs().format('YYYY-MM-DD');
                let weather = daily.find(el => el.fxDate == today);
                let textDay = weather.textDay;
                let matchedWeather = weatherData.value.find(el => {
                    let alias = el.alias;
                    if (alias.indexOf(textDay) != -1) {
                        return el;
                    }
                });
                if (matchedWeather) {
                    activeWeather.value = matchedWeather.value;
                    bus.emit("changeWeather", matchedWeather.value);
                }
            }
        });
    }
}

/**
 * 获取书签列表
 */
async function getBookmarkData() {
    const uid = route.query.uid;
    if (uid) {
        let res = await getBookmarks(store.village, uid);
        bookmarkData.value = res;
    } else {
        proxy.$toast("没有获取到uid", 2);
    }
}
/**
 * 跳转到指定书签的视角
 * @param bookmark 
 */
function gotoBookmark(bookmark) {
    activeMark.value = bookmark.Name;
    bus.emit("setCameraInfo", bookmark);
}
/**
 * 添加书签
 */
function handleAddBookmark() {
    bus.emit("getCameraInfo");
}
/**
 * 删除书签
 */
function deleteBookmark(id) {

    delBookmark(id).then(res => {
        getBookmarkData();
    });
}
/**
 * 下载模拟报告
 */
function loadReport() {
    if (downloadTableName.value) {
        activeTool.value = 'downReport';
        let dateStr = dayjs().format('YYYYMMDDHHmmss');
        let fileName = store.village + store.modeCN + dateStr + ".docx"
        downloadReport(downloadTableName.value).then(res => {
            download(res, fileName);
        });
    } else {
        proxy.$toast("没有获取到tablename");
    }
}
/**
 * 下载模拟数据Excel
 */
function downloadExcelData() {
    if (downloadTableName.value) {
        activeTool.value = 'downData';
        let dateStr = dayjs().format('YYYYMMDDHHmmss');
        let fileName = store.village + store.modeCN + dateStr + ".xlsx"
        downloadExcel(downloadTableName.value).then(res => {
            download(res, fileName);
        });
    } else {
        proxy.$toast("没有获取到tablename");
    }

}
/**
 * 下载blob格式数据
 * @param res 
 * @param fileName 
 */
function download(res, fileName) {
    let blob = new Blob([res]);
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName; // 设置下载的文件名
    document.body.appendChild(a);
    a.click();
    a.remove();
}
</script>
<style scoped lang="scss">
.toolbar-wrapper {
    position: absolute;
    top: 15%;
    pointer-events: auto;
    display: flex;
    flex-direction: column;
    align-items: center;

    &.toolbar-hide {
        left: 2%;
    }

    &.toolbar-show {
        left: 23%;
    }

    .toolbar-txt {
        font-size: 28px;

        color: #CFE7FA;
        font-family: "Microsoft YaHei";
        // text-shadow: 1px 0 #000,
        //     -1px 0 #000,
        //     0 1px #000,
        //     0 -1px #000,
        //     1px 1px #000,
        //     -1px -1px #000,
        //     1px -1px #000,
        //     -1px 1px #000;
    }

    .image {
        width: 100%;
        height: 60px;
        cursor: pointer;
        object-fit: cover;
        display: block;
    }

    .tools {
        width: 106px;
        border-left: 1px solid rgba(21, 185, 151, 0.6);
        border-right: 1px solid rgba(21, 185, 151, 0.6);
        border-bottom: 1px solid rgba(21, 185, 151, 0.6);
        padding: 20px 0;
        display: flex;
        flex-direction: column;
        background-color: rgba(0, 0, 0, 0.5);
        gap: 41px;



        .panel {
            border: 1px solid rgba(21, 185, 151, 0.6);
            position: absolute;
            left: 150px;
            background: rgba(0, 0, 0, 0.5);
            padding: 20px 44px;
            opacity: 1;
        }

        .weather-panel {
            display: grid;
            grid-template-columns: repeat(7, 120px);
            column-gap: 20px;
            row-gap: 30px;
        }

        .measure-panel {
            display: grid;
            grid-template-columns: repeat(3, 120px);
            column-gap: 40px;
            row-gap: 30px;
        }
    }
}

.tool-item {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .tool-icon {
        width: 49px;
        height: 54px;
        margin-bottom: 14px;
    }

    .tool-txt {
        font-size: 28px;
        font-weight: 350;
        line-height: 36px;
        letter-spacing: 0em;
        color: #FFFFFF;
        flex-shrink: 0;
        text-wrap: nowrap;
        font-family: "Microsoft YaHei";

    }

    .del-icon {
        position: absolute;
        right: -10px;
        top: -5px;
        width: 23px;
        height: 26px;
    }
}

.roam_panel {
    border: 1px solid rgba(21, 185, 151, 0.6);
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0, 0, 0, 0.5);
    padding: 20px 44px;
    opacity: 1;
    display: grid;
    grid-template-columns: repeat(3, 150px);
    column-gap: 20px;
    row-gap: 30px;
    pointer-events: auto;
}

.normal_roam_panel {
    bottom: 4.6%;
}

.playing_roam_panel {
    bottom: 10%;
}

.sync-wrap {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.time_label {
    font-size: 28px;
    font-weight: 350;
    line-height: 26px;
    letter-spacing: 0em;
    color: #FFFFFF;
    flex-shrink: 0;
    text-wrap: nowrap;
    font-family: "Microsoft YaHei";
}

.sync_img {
    width: 50px;
    height: 27px;
    margin-left: 10px;
    cursor: pointer;
}
</style>